﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SmApiLibrary.libs;
using CM = System.Configuration.ConfigurationManager;
using SmAp.Operator.OP.ABF;
using SmAp.Operator.Interface;
using SmApiLibrary.datatypes.Interface;
using SmApiLibrary.datatypes.AbstarctFactory;
using SmApiLibrary.helps;
using Teein.LiNing.BLL;
using SmApiLibrary.Err;
using System.Web.SessionState;
using Teein.LiNing.Web.Helper;
using System.Text;


namespace Teein.H2O.Web
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    public class TweetsHandler : IHttpHandler, IRequiresSessionState
    {
        public readonly string APPKEY = CM.AppSettings["APPKEY"];
        public readonly string APPSECRET = CM.AppSettings["APPSECRET"];
        public readonly string LININGWEIBOID = CM.AppSettings["LININGWEIBOID"];

        protected IUser User
        {
            get
            {
                if (HttpContext.Current.Session["user"] != null)
                {
                    IUser user = HttpContext.Current.Session["user"] as IUser;
                    return user;
                }
                return null;
            }
        }

        protected int UserScore
        {
            get
            {
                if (HttpContext.Current.Session["UserScore"] != null)
                {
                    return int.Parse(HttpContext.Current.Session["UserScore"].ToString());
                }
                return 0;
            }
            set
            {
                if (HttpContext.Current.Session["UserScore"] != null)
                    HttpContext.Current.Session["UserScore"] = value;
                else
                    HttpContext.Current.Session.Add("UserScore", value);
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            string action = Convert.ToString(context.Request.QueryString["action"]).ToLower();

            switch (action)
            {
                case "load":
                    LoadResult(context);
                    break;
                case "submit":
                    SubmitToSina(context);
                    break;
                case "loadbilateral":
                    LoadBilateral(context);
                    break;
                default:
                    SubmitToSina(context);
                    break;
            }

            
        }

        private void LoadBilateral(HttpContext context)
        {
            context.Response.Clear();
            if(context.Session["User"] != null)
            {
                IUser user = context.Session["User"] as IUser;
                IWeiBo wb = WeiboFactory.CreateWeiBoByType(WeiBoType.Sina);
                OAuthBase oauth = wb.GetOAuth();
                oauth.ConsumerKey = APPKEY;
                oauth.ConsumerSecret = APPSECRET;

                string result = string.Empty;

                if (context.Session["oauth_token"] != null)
                {
                    oauth.Token = context.Session["oauth_token"].ToString();
                    oauth.TokenSecret = context.Session["oauth_token_secret"].ToString();
                    oauth.Verifier = context.Session["oauth_verifier"].ToString();
                }
                else
                {
                    //context.Response.Redirect("index.html");
                    result = "{'error':2}";
                    context.Response.Write(result);
                    return;
                }

                string jsonResult = OperatorABF.CreateAbstractFactory(WeiBoType.Sina).CreateTimeLine().GetFriends(50,-1,oauth);

                context.Response.Write(jsonResult);
            }
            context.Response.End();
        }

        private void SubmitToSina(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string content = context.Request.Form["resultcontent"];
            string resultscore = context.Request.Form["resultscore"];
            bool addfriend = Convert.ToBoolean(context.Request.Form["addfriend"].ToLower() == "true"?true:false);

            IWeiBo wb = WeiboFactory.CreateWeiBoByType(WeiBoType.Sina);
            OAuthBase oauth = wb.GetOAuth();
            oauth.ConsumerKey = APPKEY;
            oauth.ConsumerSecret = APPSECRET;

            string result = string.Empty;

            if (context.Session["oauth_token"] != null)
            {
                oauth.Token = context.Session["oauth_token"].ToString();
                oauth.TokenSecret = context.Session["oauth_token_secret"].ToString();
            }
            else
            {
                //context.Response.Redirect("index.html");
                result = "{'error':2}";
                context.Response.Write(result);
                return;
            }

            string userBlogUrl = "http://weibo.com/" + this.User.id;
            try
            {
                ResultDataItem rdi = new ResultHelper().GetResultDataItem(Convert.ToInt32(resultscore));
                string picPath = HttpRuntime.AppDomainAppPath + "images\\result\\"  + rdi.ResultPic;

                ITimeline tl = OperatorABF.CreateAbstractFactory(WeiBoType.Sina).CreateTimeLine();

                tl.AddWeiBo(content, picPath, oauth);

                if (addfriend)
                {
                    if (!tl.IsFriend(User.id, LININGWEIBOID, oauth).Contains("true"))
                    {
                        tl.CreateFriend(LININGWEIBOID, oauth);
                    }
                }

                result = "{'error':0,'href':'" + userBlogUrl + "'}";
                context.Session["oauth_token"] = null;
                context.Session["oauth_token_secret"] = null;
            }
            catch (WeiBoRequestException wex)
            {
                result = "{'error':1,'msg':'" + wex.Message + "'}";
            }
            catch (Exception ex)
            {
                result = "{'error':1,'msg':'新浪微博出现异常，请稍后再试'}";
            }

            context.Response.Write(result);
        }

        private void LoadResult(HttpContext context)
        {
            StringBuilder jsonResult = new StringBuilder();

            string resultscore = context.Request.QueryString["resultscore"];

            if (string.IsNullOrEmpty(resultscore))
            {
                resultscore = Convert.ToString(new Random().Next(1, 6));
            }

            ResultDataItem rdi = new ResultHelper().GetResultDataItem(Convert.ToInt32(resultscore));

            if (rdi != null)
            {
                jsonResult.AppendFormat("{{'ResultScore':'{0}','ResultContent':'{1}','ResultPic':'../images/result/{2}'}}", rdi.ResultScore, rdi.ResultContent, rdi.ResultPic);
            }
            else
            {
                jsonResult.AppendFormat("{{'ResultScore':'','ResultContent':'','ResultPic':''}}");
            }

            context.Response.Clear();
            context.Response.Write(jsonResult.ToString());
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
